/**
 * This file is a part of qloudgen-sec. 
 * You can redistribute qloudgen-sec and/or modify it under the terms of the Lesser GNU General Public License version 3. 
 * qloudgen-sec is distributed WITHOUT ANY WARRANTY. 
 *
 * See the Lesser GNU General Public License for more details at http://www.gnu.org/licenses/. 
 **/
package org.qloudgen.sec.cas.client;

import org.qloudgen.sec.cache.Cache;
import org.qloudgen.sec.cache.CacheManager;

/**
 * <p>Title: Generic Cache Storage</p>
 * <p>Description: Wrappered generic cache storage.</p>
 * <p>Copyright: qloudgen/sec 2014</p>
 * @author <a href="mailto:hyq.dd.sun@gmail.com">glue.3M</a>
 */
public abstract class CacheStorage {
	/**
	 * Cache name.
	 */
	private String cacheName = null;
	/**
	 * Cache manager.
	 */
	private CacheManager cacheManager = null;

	/**
	 * Default constructor.
	 */
	public CacheStorage() {
	}

	/**
	 * Custom constructor.
	 *
	 * @param cacheName
	 * @param cacheManager
	 */
	public CacheStorage(String cacheName , CacheManager cacheManager) {
		this.cacheName = cacheName;
		this.cacheManager = cacheManager;
	}

	/**
	 * Returns current cache name.
	 *
	 * @return String
	 */
	public String getCacheName() {
		return cacheName;
	}
	
	/**
	 * Sets current cache name.
	 *
	 * @param cacheName
	 */
	public void setCacheName(String cacheName) {
		this.cacheName = cacheName;
	}

	/**
	 * Returns current cache manager.
	 *
	 * @return CacheManager
	 */
	public CacheManager getCacheManager() {
		return cacheManager;
	}

	/**
	 * Sets current cache manager.
	 *
	 * @param cacheManager
	 */
	public void setCacheManager(CacheManager cacheManager) {
		//
		this.cacheManager = cacheManager;
		//
		afterSetCacheManager();
	}

	/**
	 * Initializes current cache manager.
	 */
	protected void afterSetCacheManager() {
		/**
		 * Sometime multiple remote instance share same infinispan server in same jvm will throw below exception, Why?
		 *
		 * RemoteCacheManagerNotStartedException:: Cannot perform operations on a cache associated with an unstarted RemoteCacheManager
		 *
		 * So we must force execute start()...
		 */
		if ( ! cacheManager.isStarted() ) {
			cacheManager.start();
		}
	}
	
	/**
	 * Returns current cache.
	 *
	 * @return Cache
	 */
	public Cache getCache() {
		return cacheManager.getCache( cacheName );
	}
	
	/**
	 * Returns the String representation.
	 *
	 * @return String
	 */
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append( "[" );
		builder.append( super.toString() );
		builder.append( "-->" );
		builder.append( "cacheName=" ).append( cacheName ).append( "," );
		builder.append( "cacheManager=" ).append( cacheManager );
		builder.append( "]" );
		//
		return builder.toString();
	}
}